<template>
    <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
         <el-alert
    title="注意：只允许第三分类设置相关参数"
    type="warning"
    show-icon
    :closable="false">
  </el-alert>
   <el-row class="vm">
       <el-col>
           <span>选择商品分类：</span>
           <el-cascader
    v-model="checkedArray"
    :options="GoodsCateList"
    :props="cascaderProps"
    @change="handleCateChange"></el-cascader>
       </el-col>
   </el-row>
    <el-tabs v-model="activeName" @tab-click="handleTabsClick">
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" :disabled="isBtnAbled" @click="addGoodsParams">添加参数</el-button>
        <el-table :data="manyParams" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :index="i" v-for="(item, i) in scope.row.attr_vals" :key="item.id" closable @close="closeTag(i,scope.row.attr_vals,scope.row)">{{item}}</el-tag>
                <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row, scope.row.attr_vals)"
  @blur="handleInputConfirm(scope.row, scope.row.attr_vals)"
  :class="['itemWidth']"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="getEditList(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteGoodsParams(scope.row.attr_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" :disabled="isBtnAbled" @click="addGoodsParams">添加属性</el-button>
        <el-table :data="onlyAttrList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :index="i" v-for="(item, i) in scope.row.attr_vals" :key="item.id" closable @close="closeTag(i,scope.row.attr_vals,scope.row)">{{item}}</el-tag>
                <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row, scope.row.attr_vals)"
  @blur="handleInputConfirm(scope.row, scope.row.attr_vals)"
  :class="['itemWidth']"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="getEditList(scope.row.attr_id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteGoodsParams(scope.row.attr_id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-tab-pane>
  </el-tabs>
    </el-card>
    <el-dialog
  :title="'添加' + textValue"
  :visible.sync="addGoodsParamsDialogVisible"
  width="50%"
  @close="closeAddGoodsParamsDiglog"
  >
  <el-form :model="params"  ref="addGoodsParamsrRef" :rules="addGoodsParamsRule">
      <el-form-item :label="textValue + '名称'" label-width="120px" prop="paramsName">
          <el-input v-model="params.paramsName"></el-input>
      </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addGoodsParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitAddGoodsParams">确 定</el-button>
  </span>
  </el-dialog>
   <el-dialog
  :title="'编辑' + textValue"
  :visible.sync="editGoodsParamsDialogVisible"
  width="50%"
  @close="closeEditGoodsParamsDiglog"
  >
  <el-form :model="editAttrList"  ref="editGoodsParamsrRef" :rules="editGoodsParamsRule">
      <el-form-item :label="textValue + '名称'" label-width="120px" prop="attr_name">
          <el-input v-model="editAttrList.attr_name"></el-input>
      </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editGoodsParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitEditGoodsParams">确 定</el-button>
  </span>
  </el-dialog>
    </div>
</template>
<script>
export default {
  name: 'params',
  data () {
    return {
      GoodsCateList: [],
      checkedArray: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeName: 'many',
      manyParams: [],
      onlyAttrList: [],
      addGoodsParamsDialogVisible: false,
      params: {
        paramsName: ''
      },
      addGoodsParamsRule: {
        paramsName: [
          { required: true, message: '请输入商品参数/属性名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10位之间的名称', trigger: 'blur' }
        ]
      },
      editGoodsParamsRule: {
        attr_name: [
          { required: true, message: '请输入商品参数/属性名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10位之间的名称', trigger: 'blur' }
        ]
      },
      editAttrList: [],
      editGoodsParamsDialogVisible: false,
      editId: ''
    }
  },
  methods: {
    async getGoodsCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.GoodsCateList = res.data
    },
    handleCateChange () {
      console.log(this.checkedArray)
      if (this.checkedArray.length !== 3) {
        this.checkedArray = []
        this.manyParams = []
        this.onlyAttrList = []
      } else {
        this.getGoodsList()
      }
    },
    async getGoodsList () {
      const { data: res } = await this.$http.get(`categories/${this.catId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return
      //   console.log(this.activeName)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyParams = res.data
        console.log(this.manyParams)
      } else {
        this.onlyAttrList = res.data
        console.log(this.onlyAttrList)
      }
    },
    handleTabsClick () {
    //   console.log(this.activeName)
      this.getGoodsList()
      this.getEditList()
    },
    addGoodsParams () {
      this.addGoodsParamsDialogVisible = true
    },
    closeAddGoodsParamsDiglog () {
      this.$refs.addGoodsParamsrRef.resetFields()
    },
    submitAddGoodsParams () {
      this.$refs.addGoodsParamsrRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.catId}/attributes`, {
          attr_name: this.params.paramsName,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('新增参数失败')
        this.$message.success('新增参数成功')
        this.getGoodsList()
      })
      this.addGoodsParamsDialogVisible = false
    },
    async getEditList (id) {
      this.editId = id
      const { data: res } = await this.$http.get(`categories/${this.catId}/attributes/${id}`, {
        params: {
          attr_sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return
      // if (this.activeName !== 'many') {
      //   this.editOnlyList = res.data
      //   console.log(this.editOnlyList)
      // } else {
      //   this.editManyList = res.data
      //   console.log(this.editManyList)
      // }
      this.editAttrList = res.data
      console.log(this.editAttrList)
      this.editGoodsParamsDialogVisible = true
    },
    closeEditGoodsParamsDiglog () {
      this.$refs.editGoodsParamsrRef.resetFields()
    },
    submitEditGoodsParams () {
      this.$refs.editGoodsParamsrRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.catId}/attributes/${this.editId}`, {
          attr_name: this.editAttrList.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$messag.error('更新失败')
        this.$message.success('更新成功')
        this.getGoodsList()
      })
      this.editGoodsParamsDialogVisible = false
    },
    async deleteGoodsParams (id) {
      const userDeleteParamsResponse = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (userDeleteParamsResponse !== 'confirm') return this.$message.info('您取消了操作')
      const { data: res } = await this.$http.delete(`categories/${this.catId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      this.getGoodsList()
    },
    handleInputConfirm (row, arr) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        arr = arr.push(row.inputValue)
        row.inputValue = ''
        row.inputVisible = false
        this.saveAttrValue(row)
      }
    },
    async saveAttrValue (row) {
      const { data: res } = await this.$http.put(`categories/${this.catId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return
      this.$message.success('成功')
    },
    showInput (data) {
      data.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    closeTag (i, arr, row) {
      arr.splice(i, 1)
      this.saveAttrValue(row)
    }
  },
  created () {
    this.getGoodsCateList()
  },
  computed: {
    isBtnAbled () {
      if (this.checkedArray.length !== 3) {
        return true
      }
      return false
    },
    catId () {
      if (this.checkedArray.length === 3) {
        return this.checkedArray[2]
      }
      return null
    },
    textValue () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.vm{
    margin:15px 0;
}
.el-tag {
  margin: 7px
}
.itemWidth {
  width: 15%
}
</style>
